package cn.shenshen.shop;

import cn.shenshen.shop.feign.UserTokenFeignApi;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieRefreshFilter extends ZuulFilter {

    @Autowired
    private UserTokenFeignApi userTokenFeignApi;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 3;
    }

    //判断是否需要过滤
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            return false;
        }
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if("USER_TOKEN".equals(cookieName)){//需要过滤
                String token = cookie.getValue();
                ctx.set("USER_TOKEN",token);
                return true;
            }
        }
        return false;
    }

    //开始真正的过滤操作
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        String token = (String) ctx.get("USER_TOKEN");
        //1 更新cookie信息
        HttpServletResponse response = ctx.getResponse();
        Cookie cookie = new Cookie("USER_TOKEN",token);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(1800);
        response.addCookie(cookie);
        //2 更新redis的token
        userTokenFeignApi.refreshToken(token);
        return null;
    }
}
